/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tuoc;

import java.sql.ResultSet;
import java.util.Map;
import java.util.Vector;

/**
 *
 * @author apple
 */
public class products_model extends My_model{
    
    int id;
    String name;
    String unit;
    double price;
    
    
//    --------------------- FUNCTIONS
    public Vector get_elements()
    {
        ResultSet rs = this.executeSqlString("SELECT * FROM products");
        return this.to_domain_models(rs);
    }
    
    public products_model get_element_by_id(String id)
    {
        ResultSet rs = this.executeSqlString("SELECT * FROM products WHERE id = " + id);
        return this.to_domain_model(rs);
    }
    
    public Vector get_elements_by_keyword(String key)
    {
        ResultSet rs = this.executeSqlString("SELECT * FROM products WHERE name LIKE '%"+key+"%'");
        return this.to_domain_models(rs);
    }
    
    public boolean insert_data(Map<String,String> data)
    {
        String sqlString = String.format("INSERT INTO products VALUES(NULL,'%s','%s','%s')",
                (data.get("name") != null) ? data.get("name") : "",
                (data.get("unit") != null) ? data.get("unit") : "",
                (data.get("price") != null && !data.get("price").equals("")) ? data.get("price") : "0"
                );
        
        int result = this.insertDatabase(sqlString);
        return (result != -1) ? true : false;
    }
    
    
//  ---------------------------  TO MODEL
    
    
    public products_model to_domain_model(ResultSet rs)
    {
        products_model result = new products_model();
        try {
            if(rs.next())
            {
                result.id = rs.getInt("id");
                result.name = rs.getString("name");
                result.unit = rs.getString("unit");
                result.price = rs.getDouble("price");
            }    
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }
    
    public Vector to_domain_models(ResultSet rs)
    {
        Vector result = new Vector();
        try {
            while(rs.next())
            {
                products_model item = new products_model();
                item.id = rs.getInt("id");
                item.name = rs.getString("name");
                item.unit = rs.getString("unit");
                item.price = rs.getDouble("price");
                result.add(item);
            }
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }
    
}
